package org.alex.samples.service;

import java.util.ArrayList;
import java.util.List;

import org.alex.samples.dao.IUserAndSubjectDAO;
import org.alex.samples.model.UserAndSubject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserAndSubjectServiceDAO implements IUserAndSubjectService {

	@Autowired
	private IUserAndSubjectDAO iUserAndSubjectDAO;

	@Override
	public List<String> getAllUserBySubject(Integer subjectId) {
		return iUserAndSubjectDAO.getAllUserBySubject(subjectId);
	}

	@Override
	public void insertSubjectUsers(List<String> insertList, Integer subjectId) {
		UserAndSubject userAndSubject = null;
		for (int i = 0; i < insertList.size(); i++) {
			userAndSubject = new UserAndSubject();
			userAndSubject.setSubId(subjectId);
			userAndSubject.setUserId(insertList.get(i));
			iUserAndSubjectDAO.save(userAndSubject);
		}
	}

	@Override
	public void deleteSubjectUser(List<String> deleteList, Integer subjectId) {
		UserAndSubject userAndSubject = null;
		for (int i = 0; i < deleteList.size(); i++) {
			userAndSubject = new UserAndSubject();
			userAndSubject.setSubId(subjectId);
			userAndSubject.setUserId(deleteList.get(i));
			iUserAndSubjectDAO.delete(userAndSubject);
		}
	}

	@Override
	public List<String> getAllSubjectByUserId(String userId) {
		return iUserAndSubjectDAO.getAllSubjectBySubject(userId);
	}

	@Override
	public void savaUserAndSubjectByUserId(List<String> list, String userId) {
		List<String> examSubjects = getAllSubjectByUserId(userId);

		List<String> insertList = new ArrayList<String>();
		List<String> deleteList = new ArrayList<String>();

		for (String selectedSubject : list) {
			if (!examSubjects.contains(selectedSubject)) {
				insertList.add(selectedSubject);
			}
		}

		for (String selectedSubject : examSubjects) {
			if (!list.contains(selectedSubject)) {
				deleteList.add(selectedSubject);
			}
		}

		iUserAndSubjectDAO.insertUserSubjects(insertList, userId);
		iUserAndSubjectDAO.deleteUserSubjects(deleteList, userId);
		/*iUserAndSubjectService.insertSubjectUsers(insertList, subjectId);
		iUserAndSubjectService.deleteSubjectUser(deleteList, subjectId);*/

	}

	@Override
	public List<UserAndSubject> getUserAndSubjects(String userId) {
		List<UserAndSubject> list = iUserAndSubjectDAO.find("from UserAndSubject as uas where uas.userId = " + String.valueOf(userId));
		return list;
	}

}
